In C, an array is a collection of elements of the same data type, stored in contiguous memory locations. It provides a way to store multiple values of the same data type under a single variable name. The elements in an array can be accessed using their index, which starts from 0 and goes up to the array size minus one.
To declare an array in C, you specify the data type of the elements followedby the array name and the size of the array in square brackets.
data_type array_name[size];
#include <stdio.h>
int main() {
// Declaration and initialization of an integer array
int numbers[5] = {10, 20, 30, 40, 50};
// Accessing array elements using index
printf("Array Elements: ");
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
// Modifying array elements
numbers[2] = 35; // Change the value at index 2 to 35
// Accessing and printing the modified array
printf("Modified Array: ");
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
// Calculate the sum of all elements in the array
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += numbers[i];
}
printf("Sum of array elements: %d\n", sum);
return 0;
}
Array Elements: 10 20 30 40 50
Modified Array: 10 20 35 40 50
Sum of array elements: 155
What is a collection of elements of the same data type in C?
What is the position of the first element in an array in C?
What do you use to access elements in an array in C?
What is the maximum number of dimensions an array can have in C?
What C keyword is used to declare an array?